package com.tezign.intelligence.mini.dam.aifamilyconsultant.util;

import com.alibaba.dashscope.audio.tts.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.tts.SpeechSynthesizer;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.github.cdimascio.dotenv.Dotenv;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;

import static com.tezign.intelligence.mini.dam.aifamilyconsultant.constant.Constant.DASHSCOPE_API_KEY;

/**
 * https://help.aliyun.com/zh/model-studio/developer-reference/sambert-quick-start?spm=a2c4g.11186623.help-menu-2400256.d_3_3_7_1.36401d1cMXxiqv
 *
 * @Author ouyangkang
 * @date 2024/11/18
 */

public class TtsUtil {

	public static void SyncAudioDataToFile() throws Exception {

		Dotenv dotenv = Dotenv.load();
		String dashscopeApiKey = dotenv.get(DASHSCOPE_API_KEY);
		if (dashscopeApiKey == null) {
			throw new NoApiKeyException();
		}

		SpeechSynthesizer synthesizer = new SpeechSynthesizer();
		SpeechSynthesisParam param =
				SpeechSynthesisParam.builder()
						.apiKey(dashscopeApiKey)
						.model("sambert-zhichu-v1")
						.text("今天天气怎么样")
						.sampleRate(48000)
						.build();

		File file = new File("output.wav");
		// 调用call方法，传入param参数，获取合成音频
		ByteBuffer audio = synthesizer.call(param);
		try (FileOutputStream fos = new FileOutputStream(file)) {
			fos.write(audio.array());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static void main(String[] args) throws Exception {
		SyncAudioDataToFile();
		System.exit(0);
	}
}
